import { useState, useEffect } from "react";
import { Popup, Toast } from "antd-mobile";
import { isWebView, isIosApp, isAndroidApp } from "@/utils/utils";

// 自定义Hook：用于处理麦克风权限请求
const useVoicePermission = () => {
  const [hasVoicePermission, setHasVoicePermission] = useState(false);
  // useEffect(() => {
  //   const getVoicePermissionResult = (event: any) => {
  //     console.log("🚀 ~ getVoicePermissionResult ~ event:", event);
  //     if (event.data === "granted") {
  //       setHasPermission(true);
  //     } else if (event.data === "denied") {
  //       setHasPermission(false);
  //       showVoicePermissionErrMsg();
  //     }
  //   };// 监听message事件
  //   window.addEventListener("message", handlePermissionResult);
  //   // 清理函数
  //   return () => {
  //     window.removeEventListener("message", handlePermissionResult);
  //   };
  // }, []);
  const getVoicePermissionResult = (result: string): void => {
    if (result === "success") {
      setHasVoicePermission(true);
    } else {
      setHasVoicePermission(false);
      showVoicePermissionErrMsg();
    }
  };
  (window as any).getVoicePermissionResult = getVoicePermissionResult;
  // 请求权限的函数
  const requestVoicePermission = (): void => {
    if (isWebView()) {
      if (isIosApp()) {
        (window as any).webkit.messageHandlers.RequestPermission.postMessage(
          "micro",
        );
      }
      if (isAndroidApp()) {
        (window as any).Android?.requestVoicePermission(
          getVoicePermissionResult,
        );
      }
    } else {
      navigator.permissions
        .query({ name: "microphone" as PermissionName })
        .then((result) => {
          console.log("🚀 ~ .then ~ result:", result)
          if (result.state === "granted") {
            setHasVoicePermission(true);
          } else {
            setHasVoicePermission(false);
            showVoicePermissionErrMsg();
          }
        });
    }
  };
  return { hasVoicePermission, requestVoicePermission };
};
const showVoicePermissionErrMsg = (): void => {
  Toast.show({
    content: (
      <div>
        <p>
          很抱歉，当前应用无法访问您的设备麦克风。请前往系统设置重新授权，以正常使用语音录制功能：
        </p>
        <p>退出应用：先关闭此应用，确保返回手机主屏幕。</p>
        <p>打开设置：找到并进入手机的“设置”应用。</p>
        <p>
          权限管理：在设置中查找并进入“权限管理”、“应用权限”、“应用权限管理”或类似的选项。
        </p>
        <p>选择本应用：在权限列表中找到并点击您的应用名称。</p>
        <p>
          麦克风权限：在应用权限详情中，找到“麦克风”或“录音”项，将其设置为“允许”或“开启”。
        </p>
      </div>
    ),
  });
};
export { useVoicePermission, showVoicePermissionErrMsg };
